<?php

namespace MicroCyanHelper\Plan\Tool\Helper\ObjectStorage;

class Minio
{

    /**
     * @var \Aws\S3\S3Client
     */
    protected $client = null;
    /**
     * @var array
     */
    protected $config = [];
    /**
     * @param array $config
     */
    public function __construct(array $config=[])
    {
        $this->config = $config??[];
        $_cfg = [
            'version' => 'latest',
            'region'  => 'cn-east-1',
            'endpoint'=> 'http://127.0.0.1:9000',
            'use_path_style_endpoint'=>false,
            'credentials'=>[ 'key'=>'','secret'=>'' ]
        ];
        $cfg = [];
        foreach ($_cfg as $key => $def) $cfg[$key] = $this->config['ObjectStorage'][$key]??$def;
        foreach ($_cfg['credentials'] as $key => $def) $cfg['credentials'][$key] = $this->config['ObjectStorage']['credentials'][$key]??$def;
        $this->client = new \Aws\S3\S3Client($cfg);
    }

    public function putObject($filename,$content){
        $bucket = $this->config['ObjectStorage']['bucket']??'';
        $endpoint = $this->client->getEndpoint()->jsonSerialize();
        $url = $this->config['ObjectStorage']['url']??'';
        $url = preg_replace('/\/{1,}$/',"",$url);

        $puttedURL = $this->client->putObject([ 'Bucket'=>$bucket, 'Key'=>$filename, 'Body'=>$content ]);
        $puttedURL = $puttedURL['ObjectURL']??'';
        if (empty($puttedURL)) throw new \Exception('上传失败');

        if (!empty($url)){
            $puttedURL = preg_replace("/\/{2,}/",'/',"{$url}/$filename");
            $puttedURL = str_replace(':/','://',$puttedURL);
        }
        return $puttedURL;
    }

    public function getObjects(array $params,bool $url = true): array
    {
        $bucket = $this->config['ObjectStorage']['bucket']??'';
        $endpoint = $this->client->getEndpoint()->jsonSerialize();

        if ($url){
            $url = $this->config['ObjectStorage']['url']??'';
            $url = preg_replace('/\/{1,}$/',"",$url);
        }else{
            $url = '';
        }

        $params['Bucket'] = $bucket;
        $params['delimiter'] = '';
        foreach ($params as $paramKey => $paramValue) {
            unset($params[$paramKey]);
            $params[ucfirst($paramKey)]=$paramValue;
        }
        $objects = $this->client->listObjects($params)->toArray()??[];
        $objects['Contents'] = $objects['Contents']??[];
        $objects['EditVersion'] = [];

        foreach ($objects['Contents'] as $index => $content){
            $objects['EditVersion'][] = $content['LastModified']->getTimestamp();
            if (!empty($url)){
                $objects['Contents'][$index]['URL'] = "{$url}/{$content['Key']}";
            }else{
                $objects['Contents'][$index]['URL'] = "{$endpoint}/{$bucket}/{$content['Key']}";
            }
            $objects['Contents'][$index]['URL'] = preg_replace("/\/{2,}/",'/',$objects['Contents'][$index]['URL']);
            $objects['Contents'][$index]['URL'] = str_replace(":/",'://',$objects['Contents'][$index]['URL']);
        }
        sort($objects['EditVersion']);
        $objects['EditVersion'] = md5(serialize($objects['EditVersion']));
        return $objects;
    }

}